package org.example.controller;

import org.example.entity.ServiceRequest;
import org.example.service.ServiceRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 服务申请控制器
 */
@RestController
@RequestMapping("/api/service-requests")
@CrossOrigin(origins = "*")
public class ServiceRequestController {
    
    @Autowired
    private ServiceRequestService serviceRequestService;
    
    /**
     * 创建服务申请
     */
    @PostMapping
    public ResponseEntity<?> createServiceRequest(@Valid @RequestBody ServiceRequestCreateRequest request) {
        try {
            ServiceRequest serviceRequest = new ServiceRequest(
                request.getUserId(),
                request.getContactPerson(),
                request.getContactPhone(),
                request.getServiceAddress(),
                request.getAppointmentTime(),
                request.getDeviceInfo(),
                request.getProblemDescription(),
                request.getUrgencyLevel()
            );
            
            ServiceRequest createdRequest = serviceRequestService.createServiceRequest(serviceRequest);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "服务申请提交成功");
            response.put("serviceRequest", createdRequest);
            
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body("提交失败: " + e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("提交失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取服务申请详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getServiceRequest(@PathVariable Long id) {
        try {
            Optional<ServiceRequest> serviceRequest = serviceRequestService.findById(id);
            if (serviceRequest.isPresent()) {
                return ResponseEntity.ok(serviceRequest.get());
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户的服务申请列表
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getUserServiceRequests(@PathVariable Long userId) {
        try {
            List<ServiceRequest> serviceRequests = serviceRequestService.findByUserId(userId);
            return ResponseEntity.ok(serviceRequests);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取失败: " + e.getMessage());
        }
    }
    
    /**
     * 分页获取用户的服务申请列表
     */
    @GetMapping("/user/{userId}/page")
    public ResponseEntity<?> getUserServiceRequestsPage(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<ServiceRequest> serviceRequests = serviceRequestService.findByUserId(userId, pageable);
            return ResponseEntity.ok(serviceRequests);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有服务申请（管理员和维修师傅）
     */
    @GetMapping
    public ResponseEntity<?> getAllServiceRequests(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<ServiceRequest> serviceRequests = serviceRequestService.findAllServiceRequests(pageable);
            return ResponseEntity.ok(serviceRequests);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据状态获取服务申请
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<?> getServiceRequestsByStatus(
            @PathVariable String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<ServiceRequest> serviceRequests = serviceRequestService.findByStatus(status, pageable);
            return ResponseEntity.ok(serviceRequests);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取紧急待处理的服务申请
     */
    @GetMapping("/urgent")
    public ResponseEntity<?> getUrgentPendingRequests() {
        try {
            List<ServiceRequest> serviceRequests = serviceRequestService.findUrgentPendingRequests();
            return ResponseEntity.ok(serviceRequests);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新服务申请状态
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateStatus(@PathVariable Long id, @RequestBody StatusUpdateRequest request) {
        try {
            ServiceRequest updatedRequest = serviceRequestService.updateStatus(id, request.getStatus());
            return ResponseEntity.ok("状态更新成功");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("更新失败: " + e.getMessage());
        }
    }
    
    /**
     * 取消服务申请
     */
    @PutMapping("/{id}/cancel")
    public ResponseEntity<?> cancelServiceRequest(@PathVariable Long id) {
        try {
            ServiceRequest cancelledRequest = serviceRequestService.cancelServiceRequest(id);
            return ResponseEntity.ok("服务申请已取消");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("取消失败: " + e.getMessage());
        }
    }
    
    /**
     * 完成服务申请
     */
    @PutMapping("/{id}/complete")
    public ResponseEntity<?> completeServiceRequest(@PathVariable Long id, @RequestBody(required = false) CompleteRequest request) {
        try {
            ServiceRequest completedRequest;
            if (request != null && request.getCompletedBy() != null) {
                completedRequest = serviceRequestService.completeServiceRequest(id, request.getCompletedBy());
            } else {
                completedRequest = serviceRequestService.completeServiceRequest(id);
            }
            return ResponseEntity.ok("服务申请已完成");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("完成失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除服务申请
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteServiceRequest(@PathVariable Long id) {
        try {
            serviceRequestService.deleteServiceRequest(id);
            return ResponseEntity.ok("服务申请已删除");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("删除失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取服务申请统计
     */
    @GetMapping("/stats")
    public ResponseEntity<?> getServiceRequestStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            stats.put("total", serviceRequestService.countByStatus("PENDING") + 
                             serviceRequestService.countByStatus("IN_PROGRESS") + 
                             serviceRequestService.countByStatus("COMPLETED") + 
                             serviceRequestService.countByStatus("CANCELLED"));
            stats.put("pending", serviceRequestService.countByStatus("PENDING"));
            stats.put("inProgress", serviceRequestService.countByStatus("IN_PROGRESS"));
            stats.put("completed", serviceRequestService.countByStatus("COMPLETED"));
            stats.put("cancelled", serviceRequestService.countByStatus("CANCELLED"));
            stats.put("urgent", serviceRequestService.countByUrgencyLevel("URGENT"));
            stats.put("veryUrgent", serviceRequestService.countByUrgencyLevel("VERY_URGENT"));
            
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户服务申请统计
     */
    @GetMapping("/user/{userId}/stats")
    public ResponseEntity<?> getUserServiceRequestStats(@PathVariable Long userId) {
        try {
            Map<String, Object> stats = new HashMap<>();
            stats.put("total", serviceRequestService.countByUserId(userId));
            stats.put("pending", serviceRequestService.findByUserId(userId).stream()
                    .mapToLong(sr -> "PENDING".equals(sr.getStatus()) ? 1 : 0).sum());
            stats.put("inProgress", serviceRequestService.findByUserId(userId).stream()
                    .mapToLong(sr -> "IN_PROGRESS".equals(sr.getStatus()) ? 1 : 0).sum());
            stats.put("completed", serviceRequestService.findByUserId(userId).stream()
                    .mapToLong(sr -> "COMPLETED".equals(sr.getStatus()) ? 1 : 0).sum());
            stats.put("cancelled", serviceRequestService.findByUserId(userId).stream()
                    .mapToLong(sr -> "CANCELLED".equals(sr.getStatus()) ? 1 : 0).sum());
            
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取统计失败: " + e.getMessage());
        }
    }
    
    // 内部类：服务申请创建请求
    public static class ServiceRequestCreateRequest {
        private Long userId;
        private String contactPerson;
        private String contactPhone;
        private String serviceAddress;
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm")
        private LocalDateTime appointmentTime;
        private String deviceInfo;
        private String problemDescription;
        private String urgencyLevel = "URGENT";
        
        // Getter和Setter方法
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
        
        public String getContactPerson() { return contactPerson; }
        public void setContactPerson(String contactPerson) { this.contactPerson = contactPerson; }
        
        public String getContactPhone() { return contactPhone; }
        public void setContactPhone(String contactPhone) { this.contactPhone = contactPhone; }
        
        public String getServiceAddress() { return serviceAddress; }
        public void setServiceAddress(String serviceAddress) { this.serviceAddress = serviceAddress; }
        
        public LocalDateTime getAppointmentTime() { return appointmentTime; }
        public void setAppointmentTime(LocalDateTime appointmentTime) { this.appointmentTime = appointmentTime; }
        
        public String getDeviceInfo() { return deviceInfo; }
        public void setDeviceInfo(String deviceInfo) { this.deviceInfo = deviceInfo; }
        
        public String getProblemDescription() { return problemDescription; }
        public void setProblemDescription(String problemDescription) { this.problemDescription = problemDescription; }
        
        public String getUrgencyLevel() { return urgencyLevel; }
        public void setUrgencyLevel(String urgencyLevel) { this.urgencyLevel = urgencyLevel; }
    }
    
    // 内部类：状态更新请求
    public static class StatusUpdateRequest {
        private String status;
        
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
    }
    
    // 内部类：完成请求
    public static class CompleteRequest {
        private Long completedBy;
        
        public Long getCompletedBy() { return completedBy; }
        public void setCompletedBy(Long completedBy) { this.completedBy = completedBy; }
    }
}
